package com.mallbook.model.service;

import com.mallbook.model.exception.*;
import com.mallbook.model.mapper.AdminMapper;
import com.mallbook.model.mapper.UserMapper;
import com.mallbook.model.pojo.Admin;
import com.mallbook.model.pojo.PageBean;
import com.mallbook.model.pojo.User;
import com.mallbook.model.utils.MD5Utils;
import com.mallbook.model.utils.MallDefaultConfig;
import com.mallbook.model.utils.MybatisUtils;
import org.apache.ibatis.exceptions.PersistenceException;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;

/**
 * @Author 宋明松
 * @Version V1.0.0
 * @Date 2022-06-25
 * 管理员service层
 */
public class AdminService {

    /**
     * 新增用户
     *
     * @param name  账号
     * @param pwd   密码
     * @param state 状态
     */
    public void register(String name, String pwd, String power, Integer state) {
        AdminMapper adminMapper = MybatisUtils.getMappers(AdminMapper.class);
        Admin admin = new Admin();
        admin.setUsername(name);
        admin.setPassword(pwd);
        admin.setState(state);
        admin.setPower(power);
        try {
            int countUsername = adminMapper.findUserNumByCondition("username", admin.getUsername()); // 账号数量
            if (countUsername != 0) {
                throw new AccountExitsException("用户名已存在");
            }
            // 密码加密
            String md5Pwd = MD5Utils.stringToMD5(admin.getPassword());
            admin.setPassword(md5Pwd);
            adminMapper.add(admin);
        } catch (
                PersistenceException e) {
            throw new ServiceException("数据操作异常", e);
        }
    }

    /**
     * 检查管理员账号是否重复
     *
     * @param username
     */
    public void checkInfo(String username) {
        AdminMapper adminMapper = MybatisUtils.getMappers(AdminMapper.class);
        int countUsername = adminMapper.findUserNumByCondition("username", username); // 账号数量
        if (countUsername != 0) {
            throw new AccountExitsException("用户名已存在");
        }
    }

    /**
     * 删除用户（逻辑删除） 单条
     *
     * @param id 用户ID
     */
    public void delUser(Integer id) {
        AdminMapper adminMapper = MybatisUtils.getMappers(AdminMapper.class);
        Admin admin = new Admin();
        admin.setState(2);
        try {
            adminMapper.update(admin, id);
        } catch (
                PersistenceException e) {
            throw new ServiceException("数据操作异常", e);
        }
    }

    /**
     * 批量删除用户（逻辑删除）
     *
     * @param ids 用户ID的集合
     */
    public void delUserMore(List<Integer> ids) {
        AdminMapper adminMapper = MybatisUtils.getMappers(AdminMapper.class);
        Admin admin = new Admin();
        admin.setState(2);
        try {
            adminMapper.updateMore(ids, admin);
        } catch (
                PersistenceException e) {
            throw new ServiceException("数据操作异常", e);
        }
    }

    /**
     * 是否禁用或启用用户 单条
     *
     * @param id    用户ID
     * @param state 状态 -1 禁用，1 启用
     */
    public void disableUser(Integer id, Integer state) {
        AdminMapper adminMapper = MybatisUtils.getMappers(AdminMapper.class);
        Admin admin = new Admin();
        admin.setState(state);
        try {
            adminMapper.update(admin, id);
        } catch (
                PersistenceException e) {
            throw new ServiceException("数据操作异常", e);
        }
    }

    /**
     * 是否批量禁用或启用用户
     *
     * @param ids   用户ID的集合
     * @param state 状态 -1 禁用，1 启用
     */
    public void disableUserMore(List<Integer> ids, Integer state) {
        AdminMapper adminMapper = MybatisUtils.getMappers(AdminMapper.class);
        Admin admin = new Admin();
        admin.setState(state);
        try {
            adminMapper.updateMore(ids, admin);
        } catch (
                PersistenceException e) {
            throw new ServiceException("数据操作异常", e);
        }
    }

    /**
     * 除了 账号 注册时间 积分 其他都可以修改
     *
     * @param pwd      密码
     * @param lastTime 最后上线时间
     * @param state    状态
     * @param lastIP   最后上线IP
     * @param uid      账号ID
     */
    public void updateUser(String pwd, String power, String lastTime, Integer state, String lastIP, Integer uid) {
        AdminMapper adminMapper = MybatisUtils.getMappers(AdminMapper.class);
        Admin admin = new Admin();
        if (pwd != null) {
            admin.setPassword(MD5Utils.stringToMD5(pwd));
        }
        admin.setLastTime(lastTime);
        admin.setLastIP(lastIP);
        admin.setState(state);
        admin.setPower(power);
        try {
            adminMapper.update(admin, uid);
        } catch (
                PersistenceException e) {
            throw new ServiceException("数据操作异常", e);
        }
    }

    /**
     * 用户登录
     * 前台
     *
     * @param username 用户名
     * @param password 密码
     * @return
     */
    public Admin login(String username, String password) {
        AdminMapper adminMapper = MybatisUtils.getMappers(AdminMapper.class);
        try {
            // 判断账号是否存在,以及是否被删除
            int userNum = adminMapper.findUserNumByCondition("username", username);
            if (userNum == 0) {
                throw new AccountNotExitsException("账号不存在");
            }
            Admin admin = adminMapper.findUserByNameAndPwd(username, MD5Utils.stringToMD5(password));
            if (admin == null) {
                throw new AccountPwdErrorException("密码错误");
            }
            if (admin.getState() == 2) {
                throw new AccountNotExitsException("账号已删除");
            }
            // 登录
            // 判断账号是否被禁用
            if (admin.getState() == -1) {
                throw new AccountBanException("账号被禁");
            }
            return admin;
        } catch (
                PersistenceException e) {
            throw new ServiceException("数据操作异常", e);
        }
    }

    /**
     * 查询所有用户
     * 后台
     *
     * @return
     */
    public PageBean<Admin> getAllUsers(Integer pageNum) {

        return PageBeanAdmins.getByPage(null, pageNum);
    }

    /**
     * 多条件查询用户
     * 后台
     *
     * @param admin 封装的条件信息
     * @return
     */
    public PageBean<Admin> getUsersByCondition(Admin admin, Integer pageNum) {
        return PageBeanAdmins.getByPage(admin, pageNum);
    }

    /**
     * 查询个人信息
     *
     * @param id 账号ID
     * @return
     */
    public Admin getUser(Integer id) {
        AdminMapper adminMapper = MybatisUtils.getMappers(AdminMapper.class);
        try {
            return adminMapper.findUserById(id);
        } catch (
                PersistenceException e) {
            throw new ServiceException("数据操作异常", e);
        }
    }
}
